<?php

namespace App\Kits\Resources;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceResponse;

/**
 * 作用：将Resource对象转换为Response对象
 * Class ApiResourceResponse
 * @package App\Kits\Resources
 */
class ApiResourceResponse extends ResourceResponse
{

    /**
     * data字段非数组处理
     * @param array $data
     * @param array $with
     * @param array $additional
     * @return array
     */
    protected function wrap($data, $with = [], $additional = [])
    {
        if (is_null($data) || (!is_array($data) && !is_object($data))) {
            $data = [$this->wrapper() => $data];
            return array_merge_recursive($data, $with, $additional);
        }
        return parent::wrap($data, $with, $additional);
    }

    /**
     * @param Request $request
     * @return JsonResponse|mixed
     */
    public function toResponse($request)
    {
        if (!($this->resource instanceof ApiResource)) {
            $resource = is_object($this->resource) ? (array)$this->resource : $this->resource;
            $this->resource = new ApiResource($resource);
        }
        return $this->toResponseByModel($request);
    }

    protected function toResponseByModel(Request $request)
    {
        return tap(new ApiJsonResponse($this->wrap(
            $this->resource->resolve($request),
            $this->resource->with($request),
            $this->resource->additional
        ), $this->calculateStatus()), function ($response) use ($request) {
            $response->original = $this->resource->resource;

            $this->resource->withResponse($request, $response);
        });
    }


    protected function wrapper()
    {
        return 'data';
    }
}
